package com.lz.service.security;

import com.google.gson.Gson;
import com.lz.common.annotation.AnonymousAccess;
import com.lz.common.baseBean.R;
import com.lz.common.utils.JwtUtil;
import com.lz.service.security.config.MyUserDetails;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("/security")
public class SecurityController {

    //
    private final AuthenticationManager authenticationManager;
    private final Gson gson;
//    private final Jedis jedis;

    private final RedisTemplate redisTemplate;

    @AnonymousAccess
    @RequestMapping("/login")
//    public R<String> login(@RequestBody DoubleStr dto) {
    public R<String> login(String username, String password) {
        // TODO: implement login logic
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        if (authenticate == null) {
            throw new RuntimeException("用户名为空");
        }
        MyUserDetails userDetails = (MyUserDetails) authenticate.getPrincipal();
        String id = userDetails.getUser().getId();
        String json = gson.toJson(userDetails);

        redisTemplate.opsForValue().set("login:" + id, json, 30 * 60, java.util.concurrent.TimeUnit.SECONDS);
        MyUserDetails a = gson.fromJson(json, MyUserDetails.class);
        System.out.println(a);
        String usernameFromToken = JwtUtil.createToken(id);
        return R.success(usernameFromToken);
    }

}